/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rest.controllers;

import java.io.Serializable;
import java.util.Collection;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import rest.entities.JDOEntity;

import com.google.appengine.api.datastore.Key;

;


public class EntityController implements Serializable {

	public void createOrUpdate(JDOEntity entity) {
		PersistenceManager pm = EMF.get().getPersistenceManager();
		try {
			// if (record.getKey() == null) {
			pm.makePersistent(entity);
			// }
		} finally {
			pm.close();
		}

		// Entity phoneRecordEntity = findEntity(record.getId());
		// if (phoneRecordEntity == null) {
		// phoneRecordEntity = new Entity(ITEM_NAME);
		// }
		// phoneRecordEntity.setProperty("firstName", record.getFirstName());
		// phoneRecordEntity.setProperty("lastName", record.getLastName());
		// phoneRecordEntity.setProperty("phoneNumber",
		// record.getPhoneNumber());
		// datastore.put(phoneRecordEntity);

	}

	public void delete(JDOEntity entity) {
		PersistenceManager pm = EMF.get().getPersistenceManager();
		try {
			pm.deletePersistent(pm.getObjectById(entity.getClass(),
					entity.getKey()));
		} finally {
			pm.close();
		}
	}

	// public Entity findEntity(Key k) {
	// Query q = new Query(ITEM_NAME);
	// // Filter filter = new
	// PreparedQuery pq = datastore.prepare(q);
	// return null;
	// }

	public JDOEntity findEntity(Key k) {
		PersistenceManager em = EMF.get().getPersistenceManager();
		try {
			return (JDOEntity) em.getObjectById(k);
		} finally {
			em.close();
		}

	}

	// public Iterator<Entity> findAllEntities() {
	// Query q = new Query(ITEM_NAME);
	// PreparedQuery pq = datastore.prepare(q);
	// // System.out.println("query size:"
	// // + pq.countEntities(FetchOptions.Builder.withDefaults()));
	// return pq.asIterator();
	// // return pq.asList(FetchOptions.Builder.withDefaults());
	// }

	public Collection<JDOEntity> findAllEntities() {
		PersistenceManager em = EMF.get().getPersistenceManager();
		Query q = em.newQuery(JDOEntity.class);
		Collection<JDOEntity> entities = (Collection<JDOEntity>) q.execute();
		return entities;

		// ArrayList<PhoneRecord> phones = new ArrayList<PhoneRecord>();
		// for (Iterator<Entity> iterator = findAllEntities();
		// iterator.hasNext();) {
		// Entity result = (Entity) iterator.next();
		// PhoneRecord record = new PhoneRecord();
		// record.setFirstName((String) result.getProperty("firstName"));
		// record.setLastName((String) result.getProperty("lastName"));
		// record.setPhoneNumber((String) result.getProperty("phoneNumber"));
		// record.setId(result.getKey().getId());
		// phones.add(record);
		// }
		// // System.out.println("phones size:" + phones.size());

	}

}
